﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace server.app
{
    public sealed class BackpackManager
    {
        public const string DEFAULT_PACK_NAME = "DEFAULT";
        public const int DEFAULT_PACK_MAX = 10;
        public const int PACK_ITEM_MAX = 99;

        World _world = null;

        public BackpackManager(World world)
        {
            _world = world;
        }

        public bool CreackBackpack(string playerId, string name = DEFAULT_PACK_NAME, uint max = DEFAULT_PACK_MAX)
        {
            return _world.DataManager.Call<bool>(sqlx =>
            {
                return CreackBackpack(sqlx, playerId, name, max);
            });
        }
        public bool CreackBackpack(SQLx sqlx, string playerId, string name = DEFAULT_PACK_NAME, uint max = DEFAULT_PACK_MAX)
        {
            return _world.DataManager.TableBackpack.CreateBackpack(sqlx, new comm.objst.TableBackpack
            {
                PlayerId = playerId,
                Name = name,
                Max = (int)max,
            });
        }

        public string AddItem(SQLx sqlx, string playerId, string[] itemIds)
        {
            return _world.DataManager.TableBackpack.AddItem(sqlx, playerId, itemIds);
        }
        public string[] GetAllItem(string playerId)
        {
            var list = new List<string>();
            var allPack = _world.DataManager.TableBackpack.GetAllBackpack(playerId);
            foreach (var pack in allPack)
            {
                foreach (var item in pack.ItemDic.Values)
                {
                    list.Add(item.ItemId);
                }
            }
            return list.ToArray();
        }
        public comm.objst.BackpackInfo[] GetAllBackpack(string playerId)
        {
            var list = new List<comm.objst.BackpackInfo>();
            var itemDic = _world.ItemManager.GetAllItemDic(GetAllItem(playerId));
            var allPack = _world.DataManager.TableBackpack.GetAllBackpack(playerId);
            foreach (var pack in allPack)
            {
                var info = new comm.objst.BackpackInfo
                {
                    BackpackId = pack.BackpackId,
                    Name = pack.Name,
                    Max = pack.Max
                };
                foreach (var pos in pack.ItemDic.Keys)
                {
                    var item = pack.ItemDic[pos];
                    if (itemDic.ContainsKey(item.ItemId))
                    {
                        info.ItemDic.Add(pos, new comm.objst.ItemInfo(itemDic[item.ItemId]));
                    }
                }
                list.Add(info);
            }
            return list.ToArray();
        }
    }
}
